package org.babygo.file.protocol;

import com.ape.babygo.api.ByteArrayConveter;

public class FilePackage implements Comparable<FilePackage>{
    public static final int DATA_SIZE_DEFAULT_SIZE = 1024 * 1024; //文件包默认大小
    private short sessionId;
    private int packageIndex;
    private long totalNum;
    private byte[] data;

    public void packHead(short sessionId, int packageIndex, long totalNum){
        this.sessionId = sessionId;
        this.packageIndex = packageIndex;
        this.totalNum = totalNum;
    }

    public void packBody(byte[] data){
        this.data = data;
    }

    public byte[] toBinaryPackage(){
        int packageLen = getPackageSize();
        byte[] binaryPackage = new byte[packageLen];

        byte[] sessionIdArr = ByteArrayConveter.getByteArray(sessionId);
        System.arraycopy(sessionIdArr, 0, binaryPackage, 0, sessionIdArr.length);

        byte[] packageIndexArr = ByteArrayConveter.getByteArray(packageIndex);
        System.arraycopy(packageIndexArr, 0, binaryPackage, 0 + sessionIdArr.length, packageIndexArr.length);

        byte[] totalNumArr = ByteArrayConveter.getByteArray(totalNum);
        System.arraycopy(totalNumArr, 0, binaryPackage, 0 + sessionIdArr.length + packageIndexArr.length, totalNumArr.length);

        System.arraycopy(this.data, 0, binaryPackage, 0 + sessionIdArr.length + packageIndexArr.length + totalNumArr.length, this.data.length);
        return binaryPackage;
    }

    private int getPackageSize(){
        return 2 + 4 + 8 + this.data.length;
    }

    public void deserialization(byte[] data){
        byte[] sessionIdArr = new byte[2];
        System.arraycopy(data, 0, sessionIdArr, 0, sessionIdArr.length);
        byte[] packageIndexArr = new byte[4];
        System.arraycopy(data, 0 + sessionIdArr.length, packageIndexArr, 0, packageIndexArr.length);
        byte[] totalNumArr = new byte[8];
        System.arraycopy(data, 0 + sessionIdArr.length + packageIndexArr.length, totalNumArr, 0, totalNumArr.length);
        byte[] dataArr = new byte[data.length - sessionIdArr.length - packageIndexArr.length - totalNumArr.length];
        System.arraycopy(data, 0 + sessionIdArr.length + packageIndexArr.length + totalNumArr.length, dataArr, 0, dataArr.length);

        this.sessionId = ByteArrayConveter.getShort(sessionIdArr, 0);
        this.packageIndex = ByteArrayConveter.getInt(packageIndexArr, 0);
        this.totalNum = ByteArrayConveter.getLong(totalNumArr, 0);
        this.data = dataArr;
    }

    public short getSessionId() {
        return sessionId;
    }

    public int getPackageIndex() {
        return packageIndex;
    }

    public long getTotalNum() {
        return totalNum;
    }

    public byte[] getData() {
        return data;
    }

    @Override
    public int compareTo(FilePackage otherPackage) {
        return packageIndex - otherPackage.getPackageIndex();
    }
}